import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Button, 
  Table, 
  Space, 
  Select, 
  message, 
  Popconfirm, 
  Tag, 
  Image, 
  Upload, 
  Modal,
  Switch,
  Tooltip
} from 'antd';
import { 
  SearchOutlined, 
  ReloadOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  UploadOutlined,
  EyeOutlined,
  QuestionCircleOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { searchArticles, updateArticleStatus, deleteArticle, importArticles, toggleArticleActive, toggleArticleRecommend } from './service/api';
import type { ArticleItem, ArticleSearchParams } from './service/types';
import { ARTICLE_TABLES, getDefaultTableName, getTableCategories } from './service/tableList';
import ArticleDetail from './components/ArticleDetail';
import './Index.scss';

const { Option } = Select;

const ArticleListPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<ArticleItem[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 30,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true
  });
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [importFile, setImportFile] = useState<File | null>(null);
  const [importLoading, setImportLoading] = useState(false);
  // 记录最近更新的文章ID
  const [recentlyUpdated, setRecentlyUpdated] = useState<number[]>([]);
  // 记录最近推荐的文章ID
  const [recentlyRecommended, setRecentlyRecommended] = useState<number[]>([]);
  // 文章详情相关状态
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentArticleId, setCurrentArticleId] = useState<number | null>(null);
  // 文章编辑相关状态
  const [editVisible, setEditVisible] = useState(false);
  const [editArticleId, setEditArticleId] = useState<number | null>(null);

  // 初始设置默认值
  useEffect(() => {
    const defaultTableName = getDefaultTableName();
    form.setFieldsValue({
      tableName: defaultTableName
    });
    // 初始化时只请求一次
    fetchArticles({ tableName: defaultTableName });
  }, []);

  // 分页变化时重新加载数据
  useEffect(() => {
    const tableName = form.getFieldValue('tableName');
    // 只在非初始化时（有表名时）且分页变化时请求
    if (tableName && (pagination.current > 1 || pagination.pageSize !== 30)) {
      fetchArticles();
    }
  }, [pagination.current, pagination.pageSize]);

  // 查询文章列表
  const fetchArticles = async (searchParams?: Partial<ArticleSearchParams>) => {
    setLoading(true);
    try {
      const values = form.getFieldsValue();
      const params: ArticleSearchParams = {
        ...values,
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams
      };

      const res = await searchArticles(params);
      if (res.code === 0) {
        setData(res.data.list);
        setPagination((prev) => ({
          ...prev,
          total: res.data.total
        }));
      } else {
        message.error(res.msg || '查询失败');
      }
    } catch (error) {
      console.error('查询文章列表失败:', error);
      message.error('查询文章列表失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理表格分页
  const handleTableChange = (newPagination: any) => {
    setPagination((prev) => ({
      ...prev,
      current: newPagination.current,
      pageSize: newPagination.pageSize
    }));
  };

  // 搜索表单提交
  const handleSearch = (values: any) => {
    setPagination((prev) => ({
      ...prev,
      current: 1
    }));
    fetchArticles(values);
  };

  // 重置搜索表单
  const handleReset = () => {
    form.resetFields();
    form.setFieldsValue({
      tableName: getDefaultTableName()
    });
    setPagination((prev) => ({
      ...prev,
      current: 1
    }));
    fetchArticles();
  };

  // 切换推荐状态
  const handleToggleRecommend = async (id: number, currentValue: number) => {
    try {
      const newValue = currentValue === 1 ? 0 : 1;
      const tableName = form.getFieldValue('tableName');
      // 使用专用的推荐控制API
      const res = await toggleArticleRecommend(id, newValue, tableName);
      if (res.code === 0) {
        // 不显示成功消息以减少通知干扰
        fetchArticles();
        
        // 如果设置为推荐状态，记录ID并设置高亮效果
        if (newValue === 1) {
          setRecentlyRecommended(prev => [...prev, id]);
          // 5秒后清除高亮效果
          setTimeout(() => {
            setRecentlyRecommended(prev => prev.filter(item => item !== id));
          }, 5000);
        }
      } else {
        message.error(res.msg || '更新失败');
      }
    } catch (error) {
      console.error('更新推荐状态失败:', error);
      message.error('更新推荐状态失败，请重试');
    }
  };

  // 切换有效状态
  const handleToggleActive = async (id: number, currentValue: number) => {
    try {
      const newValue = currentValue === 1 ? 0 : 1;
      const tableName = form.getFieldValue('tableName');
      
      // 如果要设置为生效状态，显示提示消息
      if (newValue === 1) {
        Modal.confirm({
          title: '设置文章为生效状态',
          icon: <InfoCircleOutlined />,
          content: '将文章设置为生效状态后，文章的添加时间将更新为当前时间。确定要继续吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: async () => {
            await toggleActiveStatus(id, newValue, tableName);
          }
        });
      } else {
        // 直接设置为无效状态
        await toggleActiveStatus(id, newValue, tableName);
      }
    } catch (error) {
      console.error('更新有效状态失败:', error);
      message.error('更新有效状态失败，请重试');
    }
  };
  
  // 调用接口更改文章生效状态
  const toggleActiveStatus = async (id: number, active: number, tableName?: string) => {
    try {
      const res = await toggleArticleActive(id, active, tableName);
      if (res.code === 0) {
        // 如果是设置为生效状态，提示用户时间已更新并记录ID
        if (active === 1) {
          message.success('文章已设置为生效状态，添加时间已更新');
          // 记录最近更新的文章ID
          setRecentlyUpdated(prev => [...prev, id]);
          // 5秒后清除高亮效果
          setTimeout(() => {
            setRecentlyUpdated(prev => prev.filter(item => item !== id));
          }, 5000);
        }
        fetchArticles();
      } else {
        message.error(res.msg || '更新失败');
      }
    } catch (error) {
      console.error('更新有效状态失败:', error);
      message.error('更新有效状态失败，请重试');
    }
  };

  // 删除文章
  const handleDelete = async (id: number) => {
    try {
      const tableName = form.getFieldValue('tableName');
      const res = await deleteArticle(id, tableName);
      if (res.code === 0) {
        message.success('文章删除成功');
        fetchArticles();
      } else {
        message.error(res.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除文章失败:', error);
      message.error('删除文章失败，请重试');
    }
  };

  // 表名变更时刷新数据
  const handleTableNameChange = (value: string) => {
    // 重置分类
    form.setFieldsValue({ catename: undefined });
    // 重置页码
    setPagination((prev) => ({
      ...prev,
      current: 1
    }));
  };

  // 获取当前表的分类选项
  const getCurrentTableCategories = () => {
    const tableName = form.getFieldValue('tableName');
    return getTableCategories(tableName);
  };

  // 打开导入弹窗
  const showImportModal = () => {
    setImportModalVisible(true);
  };

  // 关闭导入弹窗
  const handleImportCancel = () => {
    setImportModalVisible(false);
    setImportFile(null);
    form.setFieldsValue({ importCatename: undefined });
  };

  // 上传文件变更
  const handleUploadChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'removed') {
      setImportFile(null);
      return;
    }
    
    // 修复：只使用originFileObj，它是File类型
    if (info.file.originFileObj) {
      setImportFile(info.file.originFileObj);
    }
  };

  // 上传前验证文件
  const beforeUpload = (file: File) => {
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (!isExcel) {
      message.error('只能上传.xlsx格式的Excel文件!');
      return false;
    }
    
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('文件大小不能超过5MB!');
      return false;
    }

    // 验证通过后设置文件
    setImportFile(file);
    return false; // 返回false阻止自动上传
  };

  // 执行导入
  const handleImport = async () => {
    if (!importFile || !(importFile instanceof File)) {
      message.warning('请先选择要导入的Excel文件');
      return;
    }

    setImportLoading(true);
    try {
      const tableName = form.getFieldValue('tableName');
      const catename = form.getFieldValue('importCatename');
      
      const res = await importArticles(importFile, {
        tableName,
        catename
      });
      
      if (res.code === 0) {
        const { total, success, fail, errors } = res.data;
        
        // 如果有失败记录，显示详细信息
        if (fail > 0) {
          Modal.info({
            title: '导入结果',
            content: (
              <div>
                <p>总计: {total}条记录</p>
                <p>成功: {success}条</p>
                <p>失败: {fail}条</p>
                <div style={{ marginTop: 16 }}>
                  <p>失败详情:</p>
                  <ul>
                    {errors.map((error, index) => (
                      <li key={index}>
                        {error.title}: {error.error}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            ),
            width: 480,
            okText: '确定'
          });
        } else {
          message.success(`导入成功：共导入${total}条记录`);
        }
        
        setImportModalVisible(false);
        setImportFile(null);
        fetchArticles();
      } else {
        message.error(res.msg || '导入失败');
      }
    } catch (error) {
      console.error('导入文章失败:', error);
      message.error('导入文章失败，请重试');
    } finally {
      setImportLoading(false);
    }
  };

  // 批量导入弹窗内容
  const renderImportModalContent = () => {
    const currentTable = ARTICLE_TABLES.find(t => t.value === form.getFieldValue('tableName'));
    
    return (
      <div>
        <div style={{ marginBottom: 16 }}>
          <div className="import-table-name">
            <div>
              <span style={{ fontWeight: 'bold' }}>目标数据表:</span> 
              {currentTable?.label}
            </div>
            <div style={{ marginTop: 8 }}>
              <span style={{ fontWeight: 'bold' }}>导入分类:</span> 
              <Input
                placeholder="请输入导入分类"
                style={{ width: 200, marginLeft: 8 }}
                value={form.getFieldValue('importCatename')}
                onChange={(e) => form.setFieldsValue({ importCatename: e.target.value })}
                allowClear
              />
            </div>
          </div>
          <div style={{ color: '#888', fontSize: 12, marginTop: 8 }}>
            <p>导入说明：</p>
            <ul>
              <li>文件格式要求：仅支持.xlsx格式</li>
              <li>文件大小：不超过5MB</li>
              <li>表格结构：第一列为标题(title)，第二列为内容(detail)</li>
              <li>如果第一行是表头（如"标题"），系统会自动跳过</li>
              <li>文章将导入到当前选择的数据表和分类中</li>
            </ul>
          </div>
        </div>
        
        <div className="upload-section">
          <Upload
            accept=".xlsx"
            name="file"
            beforeUpload={beforeUpload}
            onChange={handleUploadChange}
            maxCount={1}
            fileList={importFile ? [
              {
                uid: '-1',
                name: importFile.name,
                size: importFile.size,
                type: importFile.type,
                status: 'done'
              }
            ] : []}
          >
            <Button icon={<UploadOutlined />} disabled={!!importFile}>
              {importFile ? '已选择文件' : '选择Excel文件'}
            </Button>
          </Upload>
          
          {importFile && (
            <div style={{ marginTop: 16 }}>
              <div className="file-info">
                <div>
                  <span style={{ fontWeight: 'bold' }}>文件名称：</span>
                  {importFile.name}
                </div>
                <div style={{ color: '#52c41a', marginTop: 4 }}>
                  <span style={{ fontWeight: 'bold' }}>文件大小：</span>
                  {(importFile.size / 1024 / 1024).toFixed(2)}MB
                </div>
              </div>
              <Button 
                type="link" 
                danger 
                onClick={() => setImportFile(null)}
                style={{ padding: 0, height: 'auto', marginTop: 8 }}
              >
                移除文件
              </Button>
            </div>
          )}
        </div>
      </div>
    );
  };

  // 批量导入弹窗
  const renderImportModal = () => (
    <Modal
      title="批量导入文章"
      open={importModalVisible}
      onCancel={handleImportCancel}
      onOk={handleImport}
      confirmLoading={importLoading}
      width={600}
      okButtonProps={{ disabled: !importFile }}
      okText="开始导入"
    >
      {renderImportModalContent()}
    </Modal>
  );

  // 打开文章详情
  const handleViewArticle = (id: number) => {
    setCurrentArticleId(id);
    setDetailVisible(true);
  };

  // 关闭文章详情
  const handleCloseDetail = () => {
    setDetailVisible(false);
    // 延迟清除ID，避免弹窗关闭过程中出现闪烁
    setTimeout(() => {
      setCurrentArticleId(null);
    }, 300);
  };

  // 打开文章编辑弹窗
  const handleEditArticle = (id: number) => {
    setEditArticleId(id);
    setEditVisible(true);
  };

  // 关闭文章编辑弹窗
  const handleCloseEdit = () => {
    setEditVisible(false);
    // 延迟清除ID，避免弹窗关闭过程中出现闪烁
    setTimeout(() => {
      setEditArticleId(null);
    }, 300);
  };

  // 编辑成功回调
  const handleEditSuccess = () => {
    // 刷新文章列表
    fetchArticles();
    
    // 记录最近更新的文章ID
    if (editArticleId) {
      setRecentlyUpdated(prev => [...prev, editArticleId]);
      // 5秒后清除高亮效果
      setTimeout(() => {
        setRecentlyUpdated(prev => prev.filter(item => item !== editArticleId));
      }, 5000);
    }
  };

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '图片',
      dataIndex: 'imgsrc',
      key: 'imgsrc',
      width: 100,
      render: (imgsrc: string) => {
        if (imgsrc) {
          return (
            <div className="image-container">
              <Image
                src={imgsrc}
                alt="文章图片"
                className="article-image"
                preview={{
                  mask: (
                    <div className="preview-mask">
                      <EyeOutlined style={{ marginRight: 4 }} />
                      预览
                    </div>
                  )
                }}
              />
            </div>
          );
        } else {
          return <div className="empty-image">空</div>;
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      className: 'content-column',
      ellipsis: true,
    },
    {
      title: '文章简介',
      dataIndex: 'desc',
      key: 'desc',
      className: 'content-column',
      ellipsis: true,
      render: (desc: string) => {
        if (!desc) return '-';
        const shortDesc = desc.length > 20 ? `${desc.slice(0, 20)}...` : desc;
        return (
          <Tooltip title={desc}>
            {shortDesc}
          </Tooltip>
        );
      }
    },
    {
      title: '文章分类',
      dataIndex: 'catename',
      key: 'catename',
      width: 120,
    },
    {
      title: '阅读次数',
      dataIndex: 'readcount',
      key: 'readcount',
      width: 100,
      sorter: (a: ArticleItem, b: ArticleItem) => a.readcount - b.readcount,
    },
    {
      title: '是否推荐',
      dataIndex: 'recommend',
      key: 'recommend',
      width: 100,
      render: (recommend: number, record: ArticleItem) => (
        <Tooltip title={recommend === 1 ? "点击取消推荐" : "点击设为推荐"}>
          <Switch
            checked={recommend === 1}
            onChange={() => handleToggleRecommend(record.id, recommend)}
            checkedChildren="是"
            unCheckedChildren="否"
            className={recentlyRecommended.includes(record.id) ? 'status-recommended' : ''}
          />
        </Tooltip>
      ),
    },
    {
      title: '是否有效',
      dataIndex: 'active',
      key: 'active',
      width: 100,
      render: (active: number, record: ArticleItem) => (
        <Tooltip title={active === 1 ? "设置为无效将不再显示此文章" : "设置为有效后，添加时间将更新为当前时间"}>
          <Switch
            checked={active === 1}
            onChange={() => handleToggleActive(record.id, active)}
            checkedChildren="是"
            unCheckedChildren="否"
          />
        </Tooltip>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'addtime',
      key: 'addtime',
      width: 140,
      sorter: (a: ArticleItem, b: ArticleItem) => 
        new Date(a.addtime).getTime() - new Date(b.addtime).getTime(),
      render: (text: string, record: ArticleItem) => {
        // 格式化时间为两行：年月日和时分秒
        const date = new Date(text);
        const dateStr = date.toLocaleDateString('zh-CN', { 
          year: 'numeric', 
          month: '2-digit', 
          day: '2-digit' 
        }).replace(/\//g, '-');
        const timeStr = date.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit', 
          second: '2-digit',
          hour12: false 
        });
        
        return (
          <div className={`time-column ${recentlyUpdated.includes(record.id) ? 'updated-time' : ''}`}>
            <div className="date-part">{dateStr}</div>
            <div className="time-part">{timeStr}</div>
          </div>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 180,
      render: (_: any, record: ArticleItem) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            size="small"
            onClick={() => handleViewArticle(record.id)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEditArticle(record.id)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除该文章吗?"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />} size="small">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="article-list-container">
      <Card className="search-card">
        <Form
          form={form}
          onFinish={handleSearch}
          className="search-form"
          layout="vertical"
        >
          <div className="form-row">
            <Form.Item 
              name="tableName" 
              label={
                <span>
                  数据表
                  <Tooltip title="选择要查询的文章数据表">
                    <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                  </Tooltip>
                </span>
              }
              rules={[{ required: true, message: '请选择数据表' }]}
              className="form-item"
            >
              <Select
                placeholder="请选择数据表"
                onChange={handleTableNameChange}
              >
                {ARTICLE_TABLES.map(table => (
                  <Option key={table.value} value={table.value}>
                    <Tooltip title={table.description}>
                      {table.label}
                    </Tooltip>
                  </Option>
                ))}
              </Select>
            </Form.Item>
            
            <Form.Item 
              name="title" 
              label="文章标题"
              className="form-item"
            >
              <Input placeholder="请输入文章标题" allowClear />
            </Form.Item>
            
            <Form.Item 
              name="catename" 
              label="文章分类"
              className="form-item"
            >
              <Select placeholder="请选择分类" allowClear>
                {getCurrentTableCategories().map(category => (
                  <Option key={category.value} value={category.value}>
                    {category.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            
            <Form.Item 
              name="recommend" 
              label="是否推荐"
              className="form-item"
            >
              <Select placeholder="请选择" allowClear>
                <Option value={1}>推荐</Option>
                <Option value={0}>不推荐</Option>
              </Select>
            </Form.Item>

            <Form.Item 
              name="active" 
              label="是否有效"
              className="form-item"
            >
              <Select placeholder="请选择" allowClear>
                <Option value={1}>有效</Option>
                <Option value={0}>无效</Option>
              </Select>
            </Form.Item>

            <Form.Item className="form-item form-btn-item">
              <div className="form-btns">
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />} loading={loading}>
                  查询
                </Button>
                <Button icon={<ReloadOutlined />} onClick={handleReset}>
                  重置
                </Button>
              </div>
            </Form.Item>
          </div>
        </Form>
      </Card>

      <Card className="table-card">
        <div className="action-bar">
          <div className="left-actions">
            <Button type="primary" icon={<PlusOutlined />}>
              新增文章
            </Button>
            <Button icon={<UploadOutlined />} onClick={showImportModal}>
              批量导入
            </Button>
          </div>
          <div className="right-actions">
            <span className="table-info">
              当前数据表: {ARTICLE_TABLES.find(t => t.value === form.getFieldValue('tableName'))?.label}
            </span>
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          pagination={pagination}
          onChange={handleTableChange}
          loading={loading}
          scroll={{ x: 1300 }}
        />
      </Card>

      {/* 批量导入弹窗 */}
      {renderImportModal()}

      {/* 文章详情弹窗 */}
      <ArticleDetail
        visible={detailVisible}
        articleId={currentArticleId}
        tableName={form.getFieldValue('tableName') || getDefaultTableName()}
        onClose={handleCloseDetail}
      />
    </div>
  );
};

export default ArticleListPage;
 